import { styled } from '@umijs/max'
import { Button, Col, Form, Input, Modal, Row, Space, Table } from 'antd'
import { useEffect, useState } from 'react'
import { useRequest } from 'ahooks'
import { PAGINATION_CONFIG } from '@/constants'
import type { ColumnsType } from 'antd/es/table'
import type { PersonUser, QueryOrgListParams } from '@/pages/station/org/services'
import { queryPersonUserList } from '@/pages/station/org/services'
import { Access } from '@umijs/max'
import { CloseCircleFilled } from '@ant-design/icons'

const ModalContent = styled.div`
  display: flex;
  flex-direction: column;
  gap: 20px;

  .ant-form-item {
    margin: 0;
  }
`

interface SelectValue {
  id: string
  name: string
}

interface PersonSelectProps {
  value?: SelectValue
  onChange?: (value?: SelectValue) => void
  style?: React.CSSProperties
  disabled?: boolean
  allowClear?: boolean
  inline?: boolean
}

interface SelectModalProps {
  initValue?: SelectValue
  open?: boolean
  onClose?: () => void
  onSelect?: (value?: SelectValue) => void
}

const SelectModal: React.FC<SelectModalProps> = props => {
  const [searchForm] = Form.useForm<QueryOrgListParams>()
  const [searchParams, setSearchParams] = useState<QueryOrgListParams>({
    pageNum: 1, pageSize: 10,
  });
  const userList = useRequest(() => queryPersonUserList(searchParams), {
    ready: !!props.open,
    refreshDeps: [searchParams],
  })
  const [selected, setSelected] = useState<SelectValue[]>([]);

  const columns: ColumnsType<PersonUser> = [
    {
      title: '昵称',
      dataIndex: 'nickname',
    },
    {
      title: '手机号',
      dataIndex: 'telephone',
    },
  ]

  const onFinish = (formValues: QueryOrgListParams) => {
    setSearchParams({
      ...searchParams,
      ...formValues,
      pageNum: 1,
    })
  }

  const onReset = () => {
    searchForm.resetFields()
  }

  const onCancel = () => {
    props.onClose?.()
  }

  const onOk = () => {
    props.onSelect?.(selected[0])
    onCancel()
  }

  useEffect(() => {
    if (props.open) {
      setSelected(props.initValue ? [props.initValue] : [])
    } else {
      setSelected([])
    }
  }, [props.open]);

  return (
    <Modal
      open={props.open}
      width={800}
      title='选择私桩主'
      onOk={onOk}
      onCancel={onCancel}
    >
      <ModalContent>
        <Form form={searchForm} onFinish={onFinish} onReset={onReset}>
          <Row gutter={[20, 20]}>
            <Col span={8}>
              <Form.Item label='名称' name='username'>
                <Input placeholder='请输入' />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label='私桩主手机号' name='telephone'>
                <Input placeholder='请输入手机号' />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Space>
                <Button type='primary' htmlType='submit' loading={userList.loading}>筛选</Button>
                <Button onClick={onReset}>重置</Button>
              </Space>
            </Col>
          </Row>
        </Form>
        <Table<PersonUser>
          rowKey='id'
          loading={userList.loading}
          dataSource={userList.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: userList.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
          rowSelection={{
            type: 'radio',
            selectedRowKeys: selected.map(it => it.id),
            onChange: (_, rows) => {
              setSelected(rows.length ? [{id: rows[0].id, name: rows[0].nickname}] : [])
            }
          }}
        />
      </ModalContent>
    </Modal>
  )
}

const PersonSelect: React.FC<PersonSelectProps> = props => {
  const [open, setOpen] = useState(false)

  const close = () => {
    setOpen(false)
  }

  const allowClear = () => {
    props.onChange?.(undefined)
  }
  
  return <div>
    <div style={{display: 'flex', gap: 8, alignItems: 'center'}}>
      <Input
        placeholder='请选择'
        value={props.value?.name}
        disabled={props.disabled}
        style={props.style}
        readOnly
        addonAfter={props.disabled ? '选择' : <a onClick={() => setOpen(true)}>选择</a>}
        suffix={!!props.allowClear && !!props.inline && !!props.value?.name ? <CloseCircleFilled onClick={allowClear} style={{color: '#ccc'}} /> : undefined}
      />
      <Access accessible={!!props.allowClear && !props.inline}>
        <a onClick={allowClear}>清除</a>
      </Access>
    </div>
    <SelectModal
      open={open}
      onClose={close}
      initValue={props.value}
      onSelect={props.onChange}
    />
  </div>
}

export default PersonSelect
